<script setup lang="ts">
import useApplicationModelTree from './composable'
import type { TreeNodeData } from './type'
import type { TreeInstance } from 'element-plus'

defineOptions({
  inheritAttrs: false,
})

const props = withDefaults(defineProps<{
  // 模型编码
  code: string
  /** 是否默认选中第一棵树的根节点 */
  fire?: boolean
}>(), {
  fire: true,
})

const emits = defineEmits<{
  (e: 'clickNode', o: TreeNodeData): void
}>()

const { modelName, data, loading, getTreeData } = useApplicationModelTree()
const [current, setCurrent] = useState<TreeNodeData | null>(null)

const treeRef = ref<TreeInstance>()

function clickNode(o: TreeNodeData) {
  setCurrent(o)
  emits('clickNode', o)
}
function setCurrentKey(key: string) {
  treeRef.value?.setCurrentKey(key)
}

watchEffect(async () => {
  if (props.code) {
    await getTreeData(props.code)
    if (props.fire) {
      const head = unref(data)[0]
      if (head) {
        setCurrentKey(String(head.id))
        emits('clickNode', head)
      }
    }
  }
})

defineExpose({
  current,
  data,
  setCurrentKey,
})
</script>

<template>
  <div
    v-loading="loading" element-loading-custom-class="global-loading"
    class="height-fill view-tree flex-incompressible box-border"
  >
    <h5
      class="flex-incompressible align-center mb-2 mt-0 flex justify-between"
    >
      {{ modelName }}
    </h5>
    <ElScrollbar>
      <ElTree
        ref="treeRef"
        class="flex-fillRemaining"
        :data="data"
        :props="{
          label: 'name',
          children: 'children',
        }"
        highlight-current
        default-expand-all
        node-key="id"
        :expand-on-click-node="false"
        v-bind="$attrs"
        @contextmenu.prevent
        @node-click="clickNode"
      >
        <template #default="{ node }">
          <div
            class="flex-fillRemaining align-center custom-tree-node flex"
          >
            <span>{{ node.label }}</span>
          </div>
        </template>
      </ElTree>
    </ElScrollbar>
  </div>
</template>
